package com.lr.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.lr.excel.entity.ExcelData;
import com.lr.excel.service.ExcelDataService;
import com.lr.excel.service.impl.ExcelDataServiceImpl;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author liurui
 * @ad Java一对一辅导，手把手带你拿高薪！
 * @WeChat：liuliang70
 * @date 2024/6/14 14:15
 */
public class ExcelDataListener extends AnalysisEventListener<ExcelData> {


    private ExcelDataService excelDataService;

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    private final List<ExcelData> cachedDataList  = new ArrayList<>();

    public ExcelDataListener(ExcelDataService excelDataService) {
       this.excelDataService = excelDataService;
    }



    @Override
    public void invoke(ExcelData excelData, AnalysisContext analysisContext) {
        cachedDataList.add(excelData);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList.clear(); 
        }
    }

    private void saveData() {
        if (!CollectionUtils.isEmpty(cachedDataList)) {
            excelDataService.insertBatch(cachedDataList);
        }
    }




    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }


}
